/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zhouyou.view.segmentedbar.demo;


import com.zhouyou.view.segmentedbar.demo.custom.CustomToolbar;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextTool;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;

/**
 * <p>描述：关于我</p>
 * 作者： zhouyou<br>
 * 日期： 2017/11/1 20:32 <br>
 * 版本： v1.0<br>
 */
public class AboutAbility extends Ability {
    private static HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0x2323,"my_app");
    private WebView m_webview;
    private WebConfig webSetting;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_activity_about);
        getWindow().setStatusBarColor(Color.getIntColor("#303F9F"));
        m_webview = (WebView) findComponentById(ResourceTable.Id_webbrowser);
        initWebView(m_webview);
        CustomToolbar aboutCustomBar = (CustomToolbar) findComponentById(ResourceTable.Id_about_custombar);
        Image menuImage = (Image) aboutCustomBar.findComponentById(ResourceTable.Id_main_menu_image);
        Image mainBack = (Image) findComponentById(ResourceTable.Id_main_back);
        ShapeElement background = new ShapeElement(getContext(), ResourceTable.Graphic_ms__drawable);
        background.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#4050B5")));
        aboutCustomBar.setBackground(background);
        mainBack.setVisibility(Component.VISIBLE);
        mainBack.setClickedListener(component -> terminateAbility());
        Text mainTitle = (Text) findComponentById(ResourceTable.Id_main_title);
        mainTitle.setMarginLeft(260);
        aboutCustomBar.setTitle("关于我");
        menuImage.setVisibility(Component.HIDE);

    }

    public void initWebView(final WebView webView) {
        if (webView == null) {
            throw new RuntimeException(" WebView object is not null,plase invoke initWebView() !!!!");
        }
        m_webview = webView;
        webSetting = m_webview.getWebConfig();
        webView.setWebAgent(new WebAgent() {
            @Override
            public ResourceResponse processResourceRequest(WebView webview, ResourceRequest request) {
                final String authority = "example.com";
                final String rawFile = "/rawfile/";
                final String local = "/local/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webview, request);
                    }
                    if (path.startsWith(rawFile)) {
                        // 根据自定义规则访问资源文件
                        String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                            ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                            return response;
                        } catch (IOException e) {
                            HiLog.info(TAG, "open raw file failed");
                        }
                    }
                    if (path.startsWith(local)) {
                        // 根据自定义规则访问本地文件
                        String localFile = getContext().getFilesDir() + path.replace(local, "/");
                        HiLog.info(TAG, "open local file " + localFile);
                        File file = new File(localFile);
                        if (!file.exists()) {
                            HiLog.info(TAG, "file not exists");
                            return super.processResourceRequest(webview, request);
                        }
                        String mimeType = URLConnection.guessContentTypeFromName(localFile);
                        try {
                            InputStream inputStream = new FileInputStream(file);
                            ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                            return response;
                        } catch (IOException e) {
                            HiLog.info(TAG, "open local file failed");
                        }
                    }
                }
                return super.processResourceRequest(webview, request);
            }
        });
        // 加载资源文件 resources/rawfile/example.html
        m_webview.load("https://example.com/rawfile/about.html");
        webSetting.setJavaScriptPermit(true);
    }
}
